<template>
  <el-container>
    <el-header>
      <el-button type="success" style="float: left; margin-left: 20px"
                 @click="registerForm = {}; addUserDialog = true">添加用户
      </el-button>
    </el-header>
    <el-main>
      <el-table :data="users" stripe height="300" style="width: 100%" ref="table"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" :selectable="selectable"/>
        <el-table-column prop="username" label="用户名" width="180"/>
        <el-table-column prop="nickname" label="昵称" width="180"/>
        <el-table-column prop="phone" label="电话" width="180"/>
        <el-table-column prop="email" label="邮箱" width="180"/>
        <el-table-column prop="address" label="地址"/>
        <el-table-column fixed="right" label="Operations" width="120">
          <template #default="scope">
            <el-button
                type="text"
                size="small"
                @click.prevent="modifyUser(users[scope.$index])">
              编辑
            </el-button>
            <el-button
                type="text"
                size="small"
                @click.prevent="deleteUser(users[scope.$index])"
                v-show="users[scope.$index].id !== 1">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="danger" style="float: left; margin: 20px" @click="bathDelete">批量删除</el-button>
      <el-pagination
          v-model:currentPage="page"
          :page-size="size"
          layout="prev, pager, next, jumper"
          :total="total"
          @current-change="handleCurrentChange">
      </el-pagination>

    </el-main>
  </el-container>
  <el-dialog v-model="addUserDialog">
    <el-form class="register_form" label-width="80px" ref="registerForm" :model="registerForm">
      <h3>添加用户</h3>
      <el-form-item label="用户名">
        <el-input
            v-model="registerForm.username"
            type="text"
            autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="密码">
        <el-input
            v-model="registerForm.password"
            type="password"
            autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="确认密码">
        <el-input
            v-model="registerForm.re_password"
            type="password"
            autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="昵称">
        <el-input
            v-model="registerForm.nickname"
            type="text"
            autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input
            v-model="registerForm.email"
            type="text"
            autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="电话">
        <el-input
            v-model="registerForm.phone"
            type="text"
            autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="地址">
        <el-input
            v-model="registerForm.address"
            type="text"
            autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label-width="0xp">
        <el-button type="primary" @click="register">添加</el-button>
        <el-button @click="addUserDialog = false">返回</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <el-dialog v-model="modifyUserDialog">
    <el-form class="register_form" label-width="80px" ref="registerForm" :model="registerForm">
      <h3>编辑用户</h3>
      <el-form-item label="用户名">
        <el-input
            v-model="registerForm.username"
            type="text"
            autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="新密码">
        <el-input
            v-model="registerForm.password"
            type="password"
            autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="确认密码">
        <el-input
            v-model="registerForm.re_password"
            type="password"
            autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="昵称">
        <el-input
            v-model="registerForm.nickname"
            type="text"
            autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input
            v-model="registerForm.email"
            type="text"
            autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="电话">
        <el-input
            v-model="registerForm.phone"
            type="text"
            autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="地址">
        <el-input
            v-model="registerForm.address"
            type="text"
            autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="分配角色">
                <el-checkbox-group v-model="hasRoles" >
                  <el-checkbox v-for="role in roles" :label="role.des" :key="role.id"/>
                </el-checkbox-group>
      </el-form-item>
      <el-form-item label-width="0xp">
        <el-button type="primary" @click="updateUser">保存</el-button>
        <el-button @click="modifyUserDialog = false">返回</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <el-dialog v-model="deleteDialogVisible" title="警告" width="30%" center>
    <span>
      是否确定删除用户: {{ pendingDelete.map(p => p.username).toString() }}？
    </span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmDelete"
        >确定</el-button
        >
      </span>
    </template>
  </el-dialog>

</template>

<script>
import {ElMessage} from 'element-plus'
import {ref} from "vue";

export default {
  name: "UserDetails",
  data() {
    return {
      users: [],
      multipleSelection: [],
      addUserDialog: ref(false),
      registerForm: {
        username: "",
        password: "",
        re_password: "",
        email: "",
        nickname: "",
        address: "",
        phone: ""
      },
      pendingDelete: [],
      deleteDialogVisible: ref(false),
      modifyUserDialog: ref(false),
      roles: [],
      hasRoles: [],
      page: 1,
      size: 10,
      total: 0
    }
  },
  mounted() {
    this.loadUsers()
  },
  methods: {
    loadUsers() {
      let _this = this
      this.$axios.get("user/page", {params: {page: this.page, size: this.size}})
          .then(success => {
            if (success.data.code === 200) {
              _this.users = success.data.data.list
              _this.total = success.data.data.total
            } else {
              ElMessage({
                message: success.data.message,
                type: 'error'
              })
            }
          })
          .catch(fail => {
            console.log(fail);
          })
    },
    deleteUser(user) {
      this.pendingDelete = [user]
      this.deleteDialogVisible = ref(true)
    },
    modifyUser(user) {
      let _this = this
      this.registerForm = user
      if (this.roles.length === 0) {
        this.$axios.get("role/list").then(success => {
              if (success.data.code === 200) {
                _this.roles = success.data.data
              } else {
                ElMessage({
                  message: success.data.message,
                  type: 'error'
                })
              }
            }).catch(fail => {
          console.log(fail)
        })
      }
      this.$axios.post("role/has", user).then(success => {
        if (success.data.code === 200) {
          _this.hasRoles = success.data.data.map(value => value.des)
          this.modifyUserDialog = ref(true)
        } else {
          ElMessage({
            message: success.data.message,
            type: 'error'
          })
        }
      }).catch(fail => {
        console.log(fail)
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    bathDelete() {
      this.pendingDelete = this.multipleSelection
      this.deleteDialogVisible = ref(true)
    },
    selectable(row) {
      return row.id !== 1
    },
    register() {
      if (this.registerForm.password !== this.registerForm.re_password) {
        alert("两次输入的密码不一致")
        return
      }
      this.$axios.post('register', {
        username: this.registerForm.username,
        password: this.registerForm.password,
        nickname: this.registerForm.nickname,
        phone: this.registerForm.phone,
        email: this.registerForm.email,
        address: this.registerForm.address,
      }).then(success => {
        if (success.data.code === 200) {
          ElMessage({
            message: '添加成功',
            type: 'success'
          })
          this.addUserDialog = ref(false)
        } else {
          ElMessage({
            message: success.data.message,
            type: 'error'
          })
        }
      }).catch(fail => {
        console.log(fail)
      })
    },
    confirmDelete() {
      this.deleteDialogVisible = ref(false)
      let _this = this
      this.$axios.post("user/delete", this.pendingDelete)
          .then(success => {
            if (success.data.code === 200) {
              ElMessage({
                message: '删除成功',
                type: 'success'
              })
              _this.loadUsers()
            } else {
              ElMessage({
                message: success.data.message,
                type: 'error'
              })
            }
          }).catch(fail => {
        console.log(fail)
      })
    },
    updateUser() {
      let newRoles = this.hasRoles.map(value => this.roles.find(role => role.des === value))
      let _this = this
      this.$axios.post("user/update", {user: this.registerForm, hasRoles: newRoles})
      .then(success => {
        if (success.data.code === 200) {
          ElMessage({
            message: '更新成功',
            type: 'success'
          })
          _this.loadUsers()
          _this.modifyUserDialog = ref(false)
        } else {
          ElMessage({
            message: success.data.message,
            type: 'error'
          })
        }
      }).catch(fail => {
        console.log(fail)
      })
    },
    handleCurrentChange() {
      this.loadUsers()
    }
  }
}
</script>

<style scoped>

</style>